package com.thinkgem.jeesite.modules.sys.security;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.entity.Result;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.modules.sys.entity.WeChatSession;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信请求拦截 @{adminPath}wx/**
 */
public class WxApiServlet extends HttpServlet {

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handlerRequest(req,resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handlerRequest(req,resp);
    }

    private void handlerRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        if(!StringUtils.isEmpty(code)){
            //向微信服务器请求token
           WeChatSession weChatSession = getWxTokenInfo(code);
           renderString(resp,new Result(weChatSession));
        }else{
            //请求请求直接转发
            req.getRequestDispatcher(req.getRequestURL().toString()).forward(req,resp);
        }
    }

    /**
     * https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html
     * @param code
     */
    private WeChatSession getWxTokenInfo(String code) {
         String code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Global.getConfig("AppID") +
                "&secret="+ Global.getConfig("AppSecret") +"&js_code="+code+"&grant_type=authorization_code";
        String respStr = HttpUtil.get(code2SessionUrl);
        WeChatSession weChatSession = JSONUtil.toBean(respStr,WeChatSession.class);
        return weChatSession;
;    }

    /**
     * 客户端返回JSON字符串
     * @param response
     * @param object
     * @return
     */
    protected String renderString(HttpServletResponse response, Object object) {
        return renderString(response, JsonMapper.toJsonString(object), "application/json");
    }

    /**
     * 客户端返回字符串
     * @param response
     * @param string
     * @return
     */
    protected String renderString(HttpServletResponse response, String string, String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            return null;
        } catch (IOException e) {
            return null;
        }
    }
}
